package com.github.shiqiyue.myadmin.service.system.rolemenu;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.shiqiyue.myadmin.entity.system.Menu;
import com.github.shiqiyue.myadmin.entity.system.RoleMenu;
import com.github.shiqiyue.myadmin.mapper.system.RoleMenuMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wwy
 * <p>
 * <p>
 * 说明：角色-菜单权限 服务<br/>
 * 创建时间：2018-03-14
 * </p>
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class RoleMenuService extends ServiceImpl<RoleMenuMapper, RoleMenu> {

    /**
     * 列表
     *
     * @param page
     * @
     */
    public Page<RoleMenu> list(Page<RoleMenu> page, Map<String, Object> map) {
        page.setRecords(baseMapper.dataList(page, map));
        return page;
    }

    /**
     * 列表(全部)
     *
     * @
     */
    public List<RoleMenu> listAll(Map<String, Object> map) {
        return baseMapper.dataList(map);
    }

    /***
     * 更新会员菜单信息
     *
     * @param roleId
     * @param menuIds
     */
    public void updateRoleMenus(String roleId, List<String> menuIds) {
        baseMapper.delete(new EntityWrapper<RoleMenu>().eq("roleId", roleId));
        List<RoleMenu> roleMenus = new ArrayList<>(10);
        for (String menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMenuId(Long.parseLong(menuId));
            roleMenu.setRoleId(roleId);
            roleMenus.add(roleMenu);
        }
        insertBatch(roleMenus);

    }

    public List<RoleMenu> selectByRoleId(String roleId) {
        return selectList(new EntityWrapper<RoleMenu>().eq("roleId", roleId));
    }

    public List<RoleMenu> selectMoreInfoByRoleId(String roleId) {
        Map<String, Object> queryParam = new HashMap<String, Object>(1);
        queryParam.put("roleId", roleId);
        return baseMapper.selectMoreInfo(queryParam);
    }

    public List<Menu> selectAuthMenuByRoleId(String roleId, boolean allRights) {
        List<Menu> menus = baseMapper.selectAuthMenuByRoleId(roleId);
        if (allRights) {
            menus.forEach((menu) -> {
                menu.setHasAuthority(true);
            });
        }
        return menus;
    }

}
